package work.linruchang.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.expression.ExpressionUtil;
import cn.hutool.script.ScriptUtil;
import lombok.SneakyThrows;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * 增强的数学相关方法工具类
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2023/08/30
 * @since 1.8
 **/
public class EnhanceMathUtil extends MathUtil {

    // 获取JavaScript引擎实例
    private final static ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");

    /**
     * 数学表达式计算
     *
     * @param mathExpression
     * @return
     */
    @SneakyThrows
    public static Object eval(String mathExpression) {
        mathExpression = StrUtil.trim(mathExpression);
        if (StrUtil.isBlank(mathExpression)) {
            return null;
        }

        return ScriptUtil.eval(mathExpression);
    }

    /**
     * 数学表达式计算
     *
     * @param mathExpression
     * @return 结果是整数
     */
    public static Integer evalToInt(String mathExpression) {
        return Convert.toInt(eval(mathExpression));
    }

    /**
     * 数学表达式计算
     *
     * @param mathExpression
     * @return 结果是小数
     */
    public static Double evalToDouble(String mathExpression) {
        return Convert.toDouble(eval(mathExpression));
    }

    /**
     * 数学表达式计算
     *
     * @param mathExpression
     * @return 结果是大整数
     */
    public static Long evalToLong(String mathExpression) {
        return Convert.toLong(eval(mathExpression));
    }


    public static void main(String[] args) {
        Long l = evalToLong("25*2");
        Console.log(l);


        Object eval = ScriptUtil.eval("25*2");
        Console.log(eval);


        final Dict dict = Dict.create()
                .set("a", 100.3)
                .set("b", 45)
                .set("c", -199.100);
        eval = ExpressionUtil.eval("a-(b-c)", dict);
        Console.log(eval);

        SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
        Expression expression = spelExpressionParser.parseExpression("25*2");
        String value = expression.getValue(String.class);
        Console.log(value);

    }

}
